import os
from os import sep

key_order = "key_order"
key_filename = "key_filename"
key_file_path = "key_file_path"
explain_sign = "#"

"""
解决windows之下,文件名顺序排序不正确的问题;
例如: 10.txt 位居 2.txt 之前
思路: 给其名称补上指定位数之0之前缀,使它们长度一致;
例如变为: 002.txt, 010.txt
最终执行:生成的shell脚本
"""


def get_all_filenames(dirPath):
    """
    获取指定目录下的所有文件名[不含路径]
    :param dirPath: 目录路径
    :return: 文件名列表
    """
    if not os.path.isdir(dirPath):
        raise ValueError(f"路径 {dirPath} 不是一个有效的目录")

    # os.listdir 会返回目录下所有文件和文件夹的名字
    all_items = os.listdir(dirPath)

    # 过滤出文件名[排除文件夹]
    filenames = [item for item in all_items if os.path.isfile(os.path.join(dirPath, item))]
    return filenames


def get_file_order_lst(files_result, exclude_substr, dir_path: str):
    results_lst = []

    for item in files_result:
        if exclude_substr not in item:
            names = str(item).split(".")
            order = int(names[0])

            tempObject = {}
            tempObject[key_order] = order
            tempObject[key_filename] = item
            tempObject[key_file_path] = dir_path + sep + item

            results_lst.append(tempObject)
        else:
            print(explain_sign,"exclude item=", item)
    return results_lst


def generate_zeros_str(amount: int):
    zero_string = ""
    for _ in range(amount):
        zero_string += "0"
    return zero_string


def core_method(amount, dirPath, exclude_substr, explain_sign):
    unix_separator="/"
    files_result = get_all_filenames(dirPath)
    filenames_data = get_file_order_lst(files_result, exclude_substr, dirPath)

    for ele in filenames_data:
        string_length = len(str(ele[key_order]))
        print(explain_sign, ele[key_order], "length=", string_length)

        gap_num = amount - string_length
        zero_str = generate_zeros_str(gap_num)

        origin_filename = dirPath+unix_separator+ele[key_filename]
        origin_filename=str(origin_filename).replace(":","")
        origin_filename=str(origin_filename).replace("\\",unix_separator)

        new_filepath = dirPath + sep + zero_str + ele[key_filename]
        new_filepath = str(new_filepath).replace(":","")
        new_filepath = str(new_filepath).replace("\\",unix_separator)
        
        print(explain_sign, origin_filename, new_filepath)

        commandScript = f'mv "{unix_separator}{origin_filename}"'
        commandScript += f' "{unix_separator}{new_filepath}";\n'
        print(commandScript)


amount_zero = 5
exclude_substr = "desktop.ini"

dirPathLst = [
   r"",
]

for elem in dirPathLst:
    core_method(
        amount=amount_zero,
        dirPath=elem,
        exclude_substr=exclude_substr,
        explain_sign=explain_sign,
    )
